package com.powernode.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.domain.UserAddr;
import com.powernode.service.UserAddrService;
import com.powernode.utils.AuthUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Api(tags = "收获地址接口管理")
@RestController
@RequestMapping("/p/address")
public class UserAddrController {

    @Autowired
    private UserAddrService userAddrService;

    @ApiOperation("查询用户收货地址列表")
    @GetMapping("/list")
    public ResponseEntity<List<UserAddr>> loadUserAddrList() {
        String userId = AuthUtil.getLoginUserId();

        List<UserAddr> userAddrList = userAddrService.selectUserAddrList(userId);
        return ResponseEntity.ok(userAddrList);
    }

    @ApiOperation("新增收获地址")
    @PostMapping("/addAddr")
    public ResponseEntity<Void> saveUserAddr(@RequestBody UserAddr userAddr) {
        String userId = AuthUtil.getLoginUserId();
        userAddr.setUserId(userId);
        userAddrService.save(userAddr);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("根据地址标识查询地址详情")
    @GetMapping("/addrInfo/{addrId}")
    public ResponseEntity<UserAddr> loadUserAddrInfo(@PathVariable Long addrId) {
        UserAddr userAddr = userAddrService.getById(addrId);
        return ResponseEntity.ok(userAddr);
    }

    @ApiOperation("修改地址详情")
    @PutMapping("/updateAddr")
    public ResponseEntity<Void> updateUserAddr(@RequestBody UserAddr userAddr) {
        String userId = AuthUtil.getLoginUserId();
        userAddr.setUserId(userId);
        userAddr.setUpdateTime(new Date());
        userAddrService.updateById(userAddr);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("删除地址详情")
    @DeleteMapping("/deleteAddr/{addrId}")
    public ResponseEntity<Void> deleteAddr(@PathVariable Long addrId) {
        userAddrService.removeById(addrId);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("设置默认收获地址")
    @PutMapping("/defaultAddr/{addrId}")
    public ResponseEntity<Void> setDefaultAddr(@PathVariable Long addrId) {
        userAddrService.setDefaultAddr(addrId);
        return ResponseEntity.ok().build();
    }


    /////////////////////// 远程调用 ///////////////////////////
    @GetMapping("/getUserDefaultAddr")
    UserAddr getUserDefaultAddr(@RequestParam String userId){
        return userAddrService.getOne(new LambdaQueryWrapper<UserAddr>()
            .eq(UserAddr::getCommonAddr, 1)
                .eq(UserAddr::getUserId, userId)
        );
    }
}
